package edu.qd.learn.newchapter.chapter03.reflect.demo01.dao;

import edu.qd.learn.newchapter.chapter03.reflect.demo01.entity.BeanInfo;
import edu.qd.learn.newchapter.chapter03.reflect.demo01.entity.BeanResult;
import edu.qd.learn.newchapter.chapter03.reflect.demo01.entity.Dog;
import lombok.Getter;

import java.util.Vector;

/**
 * 一个用来管理和实例化类的工厂模式
 */
public class BeanFactory {

    @Getter
    private static Vector<BeanResult> pool = new Vector<>();


    /**
     * 异常处理
     *
     * @param bean 类信息
     */
//    private static void checkArgs(BeanInfo bean) {
//        if (bean.getBeanPath() == null || bean.getBeanPath().isEmpty()) {
//            throw new RuntimeException("对不起，请正确传入实例路径");
//        }
//    }

    private static Object createObject(String classPath, Class<?> bClass) {

        try {
            if (bClass != null) {
                return bClass.newInstance();
            } else {
                Class<?> aClass = Class.forName(classPath);

                Object o = aClass.newInstance();
                return o;
            }
        } catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * @param beans 用来存储大量待实例化的类信息
     */
    public static void createClassInstance(BeanInfo... beans) {
        for (BeanInfo bean : beans) {
//            checkArgs(bean);
            BeanResult br = new BeanResult();

            String path = bean.getBeanPath() == null?bean.getAClass().getName():bean.getBeanPath();

            String otherName = bean.getBeanName() == null ? path.substring(path.lastIndexOf(".") + 1) : bean.getBeanName();

            br.setBeanName(otherName);

            br.setBeanInstance(createObject(bean.getBeanPath(),bean.getAClass()));

            putBeanResultIntoPool(br);
        }
    }

    /**
     * 把生成的实例化 后的beanresult存储到池里面
     *
     * @param br 实例化以后的类的信息对象
     */
    public static void putBeanResultIntoPool(BeanResult br) {
        pool.add(br);
    }

    public static void main(String[] args) {
        BeanInfo bi = new BeanInfo(Dog.class);
        BeanInfo bi2 = new BeanInfo("edu.qd.learn.newchapter.chapter03.reflect.demo01.entity.Dog");
        BeanInfo bi1 = new BeanInfo("dog1", "edu.qd.learn.newchapter.chapter03.reflect.demo01.entity.Dog");
        BeanFactory.createClassInstance(bi, bi1,bi2);


        System.out.println(BeanFactory.getPool());
    }



}